'use strict';

const Service = require('egg').Service;
const WXBizDataCrypt = require('../lib/function/WXBizDataCrypt');

class AuthService extends Service {
  async signIn (shopId, code, encryptedData, iv) {
    const codeResult = await this.app.curl('https://api.weixin.qq.com/sns/jscode2session?appid=wx7ee13f9c800d9961&secret=477b0ced47d4252b0fffe81395ca3535&js_code=' + code + '&grant_type=authorization_code', {
      dataType: 'json'
    });

    var appId = 'wx7ee13f9c800d9961';
    var pc = new WXBizDataCrypt(appId, codeResult.data.session_key);
    var data = pc.decryptData(encryptedData, iv);

    let user = await this.app.api.users.signIn(data.unionId, shopId);

    if (user === null) {
      // data.avatarUrl;
      let avatarUrl = null;
      if (data.avatarUrl) {
        const avatarUploadResult = await this.ctx.helper.uploadFile(data.avatarUrl);
        if (avatarUploadResult && avatarUploadResult.body) {
          avatarUrl = avatarUploadResult.body.key;
        }
      }
      console.log(data.openId, data.nickName, data.unionId, avatarUrl, shopId);
      user = await this.app.api.users.signUp(data.openId, data.nickName, data.unionId, avatarUrl, shopId);
      if (user === null) {
        this.ctx.throw(409, '注册失败');
      }
    }
    return user;
  }
}
module.exports = AuthService;
